package com.dlc.yunguang.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.ViewGroup;
import butterknife.BindView;
import com.dlc.commonlibrary.adapter.BaseRecyclerAdapter;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.dialog.EditDialog;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.yunguang.adapter.ProductStatusListAdapter;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.helper.UserHelper;
import com.dlc.yunguang.model.ProductStatusListImpl;
import com.dlc.yunguang.model.intfc.ProductStatusList;
import com.dlc.yunguang.net.bean.BucaoCategoryBean;
import com.dlc.yunguang.net.bean.ProductListBean;
import com.dlc.yunguang.net.bean.RFIDListBean;
import com.dlc.yunguang.net.bean.SimpleBean;
import com.dlc.yunguang.net.protocol.StockProto;
import com.dlc.yunguang.net.protocol.TagProto;
import com.dlc.yunguang.R;
import com.dlc.yunguang.adapter.decoration.RecyclerSpace;
import com.trello.rxlifecycle.android.ActivityEvent;
import java.util.ArrayList;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ProductStatusListActivity extends BaseActivity {

    private static final String EXTRA_CATEGORY = "category";
    private static final String EXTRA_PRODUCT_LIST = "product_list";

    @BindView(R.id.title_bar) TitleBar mTitleBar;
    @BindView(R.id.recycler_view) RecyclerView mRecyclerView;

    private EditDialog mDialog;

    private ProductStatusListAdapter<RFIDListBean.DataBean.ListBean> mAdapter;
    private BucaoCategoryBean.DataBean mCategory;
    private ProductListBean.DataBean mProductList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        resolveIntent();

        mTitleBar.leftExit(this);
        mTitleBar.setTitle(mCategory.title);
        initRecyclerView();

        getData(0);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_product_status_list;
    }

    // 初始化列表
    private void initRecyclerView() {
        
        mAdapter = new ProductStatusListAdapter<>(UserHelper.get().isStorekeeper());

        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, BaseRecyclerAdapter.CommonHolder holder,
                int position) {

                RFIDListBean.DataBean.ListBean item = mAdapter.getItem(position);
                Intent intent = ProductDetailActivity.newIntent(getActivity(), item);
                startActivity(intent);
            }
        });

        mAdapter.setUnbindListener(new ProductStatusListAdapter.UnbindListener() {
            @Override
            public void onUnbind(int position) {

                RFIDListBean.DataBean.ListBean item = mAdapter.getItem(position);
                showUnbindDialog(item, position);
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.addItemDecoration(new RecyclerSpace(getResources(), 0, R.dimen.normal_24dp));
        mRecyclerView.setAdapter(mAdapter);
    }

    public static Intent newIntent(Activity activity, BucaoCategoryBean.DataBean category,
        ProductListBean.DataBean productList) {
        Intent intent = new Intent(activity, ProductStatusListActivity.class);
        intent.putExtra(EXTRA_CATEGORY, category);
        intent.putExtra(EXTRA_PRODUCT_LIST, productList);
        return intent;
    }

    private void resolveIntent() {

        Intent intent = getIntent();
        mCategory = intent.getParcelableExtra(EXTRA_CATEGORY);
        mProductList = intent.getParcelableExtra(EXTRA_PRODUCT_LIST);
    }

    /**
     * 获取数据
     */
    public void getData(int page) {
        showLoadingDialog();
        StockProto.get()
            .rfid(mCategory.id, mProductList.spec_id, page, "1000000","")
            .subscribeOn(Schedulers.io())
            .compose(this.<RFIDListBean>bindUntilEvent(ActivityEvent.DESTROY))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RFIDListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    dismissLoadingDialog();
                }

                @Override
                public void onNext(RFIDListBean rfidListBean) {
                    dismissLoadingDialog();
                    mAdapter.appendData(rfidListBean.data.list);
                }
            });
    }

    /**
     * 解绑设备
     *
     * @param item
     * @param position
     */
    private void showUnbindDialog(final ProductStatusList item, final int position) {

        if (mDialog == null) {
            mDialog = EditDialog.newDialog(this)
                .setButton(R.string.sure, R.string.cancel)
                .setTitleRes(R.string.unbind_reason)
                .setHint(R.string.input_unbind_reason);
        }

        mDialog.setOnPositiveClickListener(new EditDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClick(EditDialog dialog, @NonNull String newText,
                @NonNull String oldText) {

                if (TextUtils.isEmpty(newText)) {
                    showToast(R.string.reason_not_empty);
                    return;
                }

                dialog.dismiss();
                doUnbind(newText, item, position);
            }
        });

        mDialog.show();
    }

    /**
     * 开始解绑
     *
     * @param item
     * @param position
     */
    private void doUnbind(String reason, final ProductStatusList item, final int position) {

        final DoResultDialog doResultDialog = DoResultDialog.newDialog(this)
            .setSuccessImage(R.mipmap.ic_success)
            .setWorkingText(getString(R.string.commit_unbind_ing))
            .setSuccessText(getString(R.string.commit_unbind_success));

        doResultDialog.setCancelable(false);

        doResultDialog.showWorking();
        TagProto.get()
            .unbindRFID(reason, 1, item.getRFID())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<SimpleBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    doResultDialog.dismiss();
                    showToast("解绑失败," + e.getMessage());
                }

                @Override
                public void onNext(SimpleBean simpleBean) {
                    item.setUnbound(true);
                    mAdapter.notifyItemChanged(position);
                    doResultDialog.showResultAndDismiss(true, 1000);
                }
            });
    }

    // 假数据
    @NonNull
    private ArrayList<ProductStatusList> initFakeData() {
        ArrayList<ProductStatusList> details = new ArrayList<>();
        details.add(new ProductStatusListImpl("25625636", "纯棉毛巾", "毛巾", 12, 12, "5号仓", false));
        details.add(new ProductStatusListImpl("25625236", "纯棉毛巾", "毛巾", 12, 12, "5号仓", false));
        details.add(new ProductStatusListImpl("25625636", "纯棉毛巾", "毛巾", 12, 12, "5号仓", true));
        details.add(new ProductStatusListImpl("25615636", "纯棉毛巾", "毛巾", 12, 12, "5号仓", false));
        details.add(new ProductStatusListImpl("25625640", "纯棉毛巾", "毛巾", 12, 12, "5号仓", false));
        details.add(new ProductStatusListImpl("25625637", "纯棉毛巾", "毛巾", 12, 12, "5号仓", true));
        details.add(new ProductStatusListImpl("25625639", "纯棉毛巾", "毛巾", 12, 12, "5号仓", false));
        details.add(new ProductStatusListImpl("25625634", "纯棉毛巾", "毛巾", 12, 12, "5号仓", false));
        return details;
    }
}
